package cn.edu.zut.soft.graduate.controller;

import cn.edu.zut.soft.basic.core.model.bo.CommonResult;
import cn.edu.zut.soft.basic.core.util.MDUtil;
import cn.edu.zut.soft.graduate.base.utils.Comparator.InfoComparator;
import cn.edu.zut.soft.graduate.base.utils.RandomFileUtil;
import cn.edu.zut.soft.graduate.controller.util.IdentityUtil;
import cn.edu.zut.soft.graduate.core.constant.InfoType;
import cn.edu.zut.soft.graduate.core.constant.LoginMode;
import cn.edu.zut.soft.graduate.core.constant.Role;
import cn.edu.zut.soft.graduate.core.constant.config.IKEY;
import cn.edu.zut.soft.graduate.core.design.BasicInfoStrategy;
import cn.edu.zut.soft.graduate.core.design.ProfessionalLever;
import cn.edu.zut.soft.graduate.core.model.Impl.Identity;
import cn.edu.zut.soft.graduate.core.model.Impl.Info;
import cn.edu.zut.soft.graduate.core.query.IdentityQuery;
import cn.edu.zut.soft.graduate.core.query.InfoQuery;
import cn.edu.zut.soft.graduate.core.vo.ChangePwdVO;
import cn.edu.zut.soft.graduate.core.vo.LoginVO;
import cn.edu.zut.soft.graduate.core.vo.UserDescVO;
import cn.edu.zut.soft.graduate.topicCenter.bo.GraduateStateService;
import cn.edu.zut.soft.graduate.topicCenter.bo.IssueBO;
import cn.edu.zut.soft.graduate.userCenter.bo.IdentityBO;
import cn.edu.zut.soft.graduate.userCenter.bo.InfoBO;
import cn.edu.zut.soft.graduate.userCenter.bo.StudentBO;
import cn.edu.zut.soft.graduate.userCenter.bo.TeacherBO;
import cn.edu.zut.soft.graduate.userCenter.handler.NoGroupHandler;
import cn.edu.zut.soft.graduate.userCenter.opjo.Invite;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.Collections;
import java.util.List;


/**
 * Created by chuchuang on 16/10/28.
 */
@Controller
@RequestMapping("identity")
public class IdentityController extends BaseController {

    private final static String ADMIN = "Basicadmin";

    @Resource
    private NoGroupHandler noGroupHandler;

    @Resource
    private IdentityBO identityBO;

    @Resource
    private InfoBO infoBO;

    @Resource
    private IssueBO issueBO;

    @Resource
    private TeacherBO teacherBO;

    @Resource
    private StudentBO studentBO;

    @Resource
    private GraduateStateService graduateStateService;

    @Value("#{commonProp['randomDrawingFilePath']}")
    private String randomDrawingFilePath;

    /**
     * 用户个人信息
     *
     * @param session 用户登录信息
     * @return 用户详细信息
     */
    @RequestMapping(value = "myself", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult myself(HttpSession session) {
        LoginVO loginVO = (LoginVO) session.getAttribute("user");
        if (loginVO == null || loginVO.getId() == null) {
            return CommonResult.errorReturn("未登录,请重新登录");
        }
        return CommonResult.successReturn(identityBO.userPersonal(loginVO.getId()));
    }

    /**
     * 修改用户信息
     *
     * @param session
     * @param identity
     * @return
     */
    // FIXME: 16/10/29 拦截非修改信息
    @RequestMapping(value = "myself", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult upMySelf(HttpSession session, Identity identity) {
        LoginVO loginVO = (LoginVO) session.getAttribute("user");
        if (loginVO == null || loginVO.getId() == null) {
            return CommonResult.errorReturn("未登录,请重新登录");
        }
        identity.setId(loginVO.getId());
        // FIXME: 16/11/5 优化到拦截器中
        if (identity.getPhone() != null && !LoginMode.PHONE.isMatching(identity.getPhone())) {
            return CommonResult.errorReturn("手机号修改错误,不符合规则");
        }
        if (identity.getNoId() != null && !LoginMode.NID.isMatching(identity.getNoId())) {
            return CommonResult.errorReturn("工号/学号修改错误,不符合规则");
        }
        if (identity.getEmail() != null && !LoginMode.EMAIL.isMatching(identity.getEmail())) {
            return CommonResult.errorReturn("邮箱修改错误,不符合规则");
        }

        CommonResult result = identityBO.update(identity, loginVO.getName());
        if (identity.getPhone() != null) {
            loginVO.setPhone(identity.getPhone());
            session.setAttribute(IKEY.USER, loginVO);
        }
        return result;
    }

    /**
     * 修改密码
     *
     * @param session
     * @param changePwdVO
     * @return
     */
    @RequestMapping(value = "myself/changePwd", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult changePwd(HttpSession session, ChangePwdVO changePwdVO) {
        LoginVO loginVO = (LoginVO) session.getAttribute("user");
        if (loginVO == null || loginVO.getId() == null) {
            return CommonResult.errorReturn("未登录,请重新登录");
        }
        changePwdVO.setId(loginVO.getId());
        return identityBO.alterPwd(changePwdVO, loginVO.getName());
    }

    /**
     * 重置密码
     *
     * @param session
     * @param id
     * @return
     */
    @RequestMapping(value = "resetPwd/{id}", method = RequestMethod.PUT)
    @ResponseBody
    public CommonResult resetPwd(HttpSession session, @PathVariable("id") String id) {

        LoginVO loginVO = (LoginVO) session.getAttribute("user");
        if (loginVO == null || loginVO.getId() == null) {
            return CommonResult.errorReturn("未登录,请重新登录");
        }
        if (session.getAttribute(ADMIN) == null) {
            return CommonResult.errorReturn("不具备权限");
        }
        return CommonResult.successReturn(identityBO.resetPwd(Integer.parseInt(id), loginVO.getName()));
    }

    /**
     * 获取单个的详细信息
     *
     * @param id
     * @return
     */
    @RequestMapping("id/{id}")
    @ResponseBody
    public CommonResult get(@PathVariable("id") String id) {
        return CommonResult.successReturn(identityBO.get(Integer.valueOf(id)));
    }

    /**
     * 查询用户列表
     *
     * @param identityQuery
     * @return
     */
    @RequestMapping("list")
    @ResponseBody
    public CommonResult list(IdentityQuery identityQuery) {
        return identityBO.findByQuery(identityQuery);
    }

    /**
     * 查询某角色下的详细列表
     *
     * @param identityQuery
     * @param role
     * @return
     */
    @RequestMapping("list/{role}")
    @ResponseBody
    public CommonResult listByTea(IdentityQuery identityQuery, @PathVariable("role") Role role) {
        identityQuery.setRole(role);
        if (role == null) {
            return CommonResult.errorReturn("角色为空");
        }
        return CommonResult.successReturn(identityBO.userPersonal(identityQuery, IdentityUtil.findByRole(role)), identityQuery.getCount().intValue());
    }
//    @RequestMapping("issue/list/{role}")
//    @ResponseBody
//    public CommonResult issueList( IssueQuery issueQuery, @PathVariable("role") Role role){
//        //修改掉角色
//        issueQuery.setIdentityRole(role);
//        issueQuery.setIssuePhaseList(IKEY.statusSet);
//        CommonResult<List<Issue>> result = issueBO.findByQuery(issueQuery);
//        for (Issue issue : result.getData()){
//            issue.setTechnology(null);
//        }
//        System.out.println(result.getData());
//
//        return CommonResult.successReturn(result.getData());
//    }


    /**
     * 教师职称问题
     *
     * @param id
     * @param professionalLever
     * @param session
     * @return
     */
    @RequestMapping("info/{id}/{infoStrategy}")
    @ResponseBody
    public CommonResult upDataInfoStrategy(@PathVariable("id") String id, @PathVariable("infoStrategy") ProfessionalLever professionalLever, HttpSession session) {
        return CommonResult.successReturn(infoBO.save(professionalLever, Integer.valueOf(id), ((LoginVO) session.getAttribute("user")).getName()));
    }

    /**
     * 用户添加附属信息
     *
     * @param id
     * @param basicInfoStrategy
     * @param session
     * @return
     */
    @RequestMapping("info/basic/{id}")
    @ResponseBody
    public CommonResult addInfoStrategy(@PathVariable("id") String id, BasicInfoStrategy basicInfoStrategy, HttpSession session) {
        return CommonResult.successReturn(infoBO.save(basicInfoStrategy, Integer.valueOf(id), ((LoginVO) session.getAttribute("user")).getName()));
    }

    /**
     * 附属信息检索
     *
     * @param infoQuery
     * @return
     */
    @RequestMapping("info/select")
    @ResponseBody
    public CommonResult findInfoToUser(InfoQuery infoQuery) {
        infoQuery.setRole(Role.stu);
        return identityBO.findByInfo(infoQuery);
    }

    /**
     * 附属单个详细信息
     *
     * @param id
     * @return
     */
    @RequestMapping("info/{id}")
    @ResponseBody
    public CommonResult IdInfoList(@PathVariable("id") String id) {
        return CommonResult.successReturn(infoBO.queryByUser(Integer.valueOf(id)));
    }


    /**
     * 所有的职称
     *
     * @return
     */
    @RequestMapping("allProfessionalLever")
    @ResponseBody
    public CommonResult allProfessionalLever() {
        return CommonResult.successReturn(ProfessionalLever.getMap());
    }


    /**
     * 新建用户
     *
     * @param session
     * @param identity
     * @param role
     * @return
     */
    @RequestMapping(value = "save/{role}", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult saveTea(HttpSession session, Identity identity, @PathVariable("role") Role role) {
        LoginVO loginVO = (LoginVO) session.getAttribute("user");
        if (loginVO == null) {
            return CommonResult.errorReturn("尚未登录,请从新登录");
        }
        if (session.getAttribute(ADMIN) == null) {
            return CommonResult.errorReturn("不具备权限");
        }
        if (identity.getNoId() != null && !LoginMode.NID.isMatching(identity.getNoId())) {
            return CommonResult.errorReturn("工号/学号错误,不符合规则");
        }
        if (identity.getPhone() != null && !LoginMode.PHONE.isMatching(identity.getPhone())) {
            return CommonResult.errorReturn("手机号修改错误,不符合规则");
        }
        //设置手机为初始密码
        identity.setPwd(MDUtil.MD5(identity.getPhone()));
        identity.setRole(role);
        identityBO.save(identity, loginVO.getName());
        return CommonResult.successReturn(identity);
    }

    @ResponseBody
    @RequestMapping("/getGuideTea")
    public CommonResult getGuideTea(@RequestParam("id") Integer id) {
        if (id == null) {
            return CommonResult.errorReturn("System error");
        }
        InfoQuery infoQuery = new InfoQuery();
        infoQuery.setKey(IKEY.Guide);
        infoQuery.setIdentityId(id);
        infoQuery.setDel(0);
        List<Info> infoList = infoBO.selectExampleWithBLOB(infoQuery);
        List<Info> result = null;
        if (infoList != null) {
            InfoQuery infoQueryTea = new InfoQuery();
            if (StringUtils.isEmpty(infoList.get(0).getValue())) {
                return CommonResult.errorReturn("System error");
            }
            Integer teaId = Integer.parseInt(infoList.get(0).getValue());
            infoQueryTea.setIdentityId(teaId);
            infoQueryTea.setRole(Role.tea);
            infoQueryTea.setKey(IKEY.PROFESSIONALLEVER);
            infoQueryTea.setDel(0);
            result = infoBO.selectExampleWithBLOB(infoQueryTea);
        }
        return CommonResult.successReturn(result);
    }

    /**
     * 检索所有教师以及所带的学生情况
     *
     * @param identityQuery
     * @return
     */
    @ResponseBody
    @RequestMapping("/queryTeaOfStuName")
    public CommonResult queryTeaOfStuName(IdentityQuery identityQuery) {
        return teacherBO.queryTeaOfStuName(identityQuery);
    }


    /**
     * 检索没有小组的用户列表
     *
     * @param session
     * @param identityQuery
     * @return
     */
    @RequestMapping("/noGroupList")
    @ResponseBody
    public CommonResult noGroupList(HttpSession session, IdentityQuery identityQuery) {
        LoginVO loginVO = (LoginVO) session.getAttribute(IKEY.USER);
        Invite invite = new Invite();
        // FIXME: 16/12/12 user 无效,准备放弃
        invite.setUser(loginVO);
        if (session.getAttribute(InfoType.Basic.name() + "admin") == null) {
            invite.setRunner(Role.Runner.user);
        } else {
            invite.setRunner(Role.Runner.admin);
//            invite.setOwner(loginVO.getId());
        }
        invite.setOwner(loginVO.getId());
        identityQuery.setPageSize(Integer.MAX_VALUE);
        //修改角色为教师
//        identityQuery.setRole(Role.tea);
        invite.setIdentityQuery(identityQuery);
        return CommonResult.successReturn(identityBO.findCanInvitationUser(invite, noGroupHandler), identityQuery.getCount().intValue());
    }

    /**
     * 显示全部未分组学生数不为零的教师列表，
     */
    @RequestMapping("/noGroupAndNoStuOfTea")
    @ResponseBody
    public CommonResult noGroupAndNoStuOfTea(IdentityQuery identityQuery) {
        return teacherBO.queryNoGroupAndNoStuOfTea(identityQuery);
    }

    /**
     * 功能描述:保存答辩地址
     *
     * @param request
     * @param id
     * @param address
     * @return
     */
    @ResponseBody
    @RequestMapping("/saveAddress")
    public CommonResult saveAddress(HttpServletRequest request, @RequestParam("id") Integer id, @RequestParam("address") String address) {
        LoginVO loginVO = (LoginVO) request.getSession().getAttribute("user");
        if (loginVO == null) {
            return CommonResult.errorReturn("请重新登陆");
        }
        if (id == null || StringUtils.isEmpty(address)) {
            return CommonResult.errorReturn("System error");
        }
        Info result = infoBO.save(new BasicInfoStrategy(InfoType.Basic, IKEY.ADDRESS, address), id, loginVO.getName());
        if (result == null) {
            return CommonResult.errorReturn("System error");
        }
        return CommonResult.successReturn(result);
    }

    /**
     * 功能描述:根据小组ID 查询该小组下所有的学生
     *
     * @param identityQuery
     * @return
     */
    @ResponseBody
    @RequestMapping("/teaGroupStu")
    public CommonResult teaGroupStu(IdentityQuery identityQuery, String sort) {
//        , new InfoComparator(new Info())
        List<UserDescVO> userDescVOList = studentBO.queryStuAllByTeaGroupAndAddress(identityQuery);
            if ("StudentRegion".equals(sort)) {
                Info info = new Info();
                info.setType(InfoType.Basic.name());
                info.setKey(IKEY.ADDRESS);
                Collections.sort(userDescVOList, new InfoComparator(info));
        }
        return CommonResult.successReturn(userDescVOList, identityQuery.getCount().intValue());
    }

    @ResponseBody
    @RequestMapping("/getGradeStatus")
    public CommonResult getSystemGradeStatus(IdentityQuery identityQuery,@RequestParam("status") String status){
        List<UserDescVO> userDescVOList = studentBO.queryStuAllBySystemGrade(identityQuery, status);
        return CommonResult.successReturn(userDescVOList, identityQuery.getCount().intValue());
    }

    @ResponseBody
    @RequestMapping(value = "/randomDrawing",method = RequestMethod.POST)
    public CommonResult randomDrawing(int num) {

        File file = new File(randomDrawingFilePath);
        if (file.exists()) {
            StringBuilder sb = new StringBuilder();
            RandomFileUtil.readFile(file,sb);
            JSONObject input = JSONObject.parseObject(sb.toString());
            if (!input.getBooleanValue("use")){
                return CommonResult.errorReturn("当前文件已经存在，并且已经应用，请删除物理文件以及用户数据");
            }
        }
        CommonResult<List<UserDescVO>> result = studentBO.randomDrawing(num);
        JSONObject output = new JSONObject();
        output.put("use","true");
        output.put("data",result.getData());
        RandomFileUtil.writerFile(file, output);
        return result;

    }



    @ResponseBody
    @RequestMapping("/selectDrawing")
    public CommonResult selectDrawing() {
        File file = new File(randomDrawingFilePath);
        if (!file.exists()) {
            return CommonResult.successReturn(Collections.emptyList());
        }
        StringBuilder sb = new StringBuilder();
        RandomFileUtil.readFile(file, sb);
        JSONObject input = JSONObject.parseObject(sb.toString());
        JSONArray list = input.getJSONArray("data");
        return CommonResult.successReturn(list);
    }

    @ResponseBody
    @RequestMapping("/stateFindByUser")
    private CommonResult stateFindByUser(Integer userId){
        return CommonResult.successReturn(graduateStateService.findByUser(userId));

    }

}
